package top.ahzy.seobench.controller;

import cn.hutool.json.JSONUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import top.ahzy.seobench.config.JWTConfig;
import top.ahzy.seobench.model.dto.MessageDto;
import top.ahzy.seobench.model.entity.User;
import top.ahzy.seobench.model.rsp.MessageOnLineRsp;
import top.ahzy.seobench.result.Result;
import top.ahzy.seobench.service.MessageService;
import top.ahzy.seobench.sparkLite.SparkService;
import top.ahzy.seobench.util.JwtUtil;
import top.ahzy.seobench.websocket.MessageSocket;

import javax.servlet.http.HttpServletRequest;


/**
 * @author ahzy
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/message")
@Api(tags = "message模块")
public class MessageController {

    @Autowired
    private MessageSocket messageSocket;

    @Autowired
    private MessageService messageService;

    @Autowired
    private SparkService sparkService;

    @GetMapping("/sendMsg")
    @ApiOperation(value = "发送消息", notes = "")
    public Boolean sendMsg(@ApiParam(value = "消费者id") @RequestParam("comsumerId") String comsumerId,
                           @ApiParam(value = "消息") @RequestParam("content") String content) {
        MessageDto message = new MessageDto();
        message.setComsumerId(comsumerId);
        message.setContent(content);
        return messageSocket.sendMsg(message);
    }

    @GetMapping("/toAll")
    @ApiOperation(value = "广播", notes = "")
    public Boolean sendMsg(@ApiParam(value = "消息") @RequestParam("message") String massage) {
        return messageSocket.toAll(massage);
    }

    @GetMapping("/getOnLine")
    @ApiOperation(value = "获取在线情况", notes = "")
    public Result<MessageOnLineRsp>  getOnLine() {
        return Result.success(messageService.getOnLine());
    }

    @PostMapping("/sendSpark")
    @ApiOperation(value = "提问星火", notes = "")
    public Result sendSpark(HttpServletRequest request,@RequestBody String body) {
        String context = JSONUtil.parseObj(body).getStr("context");
        String token = request.getHeader(JWTConfig.tokenHeader);
        User user = JwtUtil.parseAccessToken(token);
        assert user != null;
        sparkService.send(user.getUsername(),context);
        return Result.success();
    }


}
